import preferences from '@ohos.data.preferences'
import { CommonConstants } from '../constants/CommonConstants'
import Logger from './Logger'

class PreferenceUtil {
  private INSTANCE: preferences.Preferences

  async init(context) {
    try {
      this.INSTANCE = await preferences.getPreferences(context, CommonConstants.PreferenceName)
      Logger.debug(`加载Preferences[${CommonConstants.PreferenceName}成功`)
    } catch (e) {
      Logger.debug(`加载Preferences[${CommonConstants.PreferenceName}失败`)
    }
  }

  async put(key: string, value: preferences.ValueType) {
    if (!this.INSTANCE) {
      Logger.debug(`未加载Preferences[${CommonConstants.PreferenceName}`)
      return
    }
    await this.INSTANCE.put(key, value)
    await this.INSTANCE.flush()
    Logger.debug(`保存Preferences[${CommonConstants.PreferenceName}成功`)
  }

  async get(key: string, defaultValue: preferences.ValueType) {
    try {

      let value = this.INSTANCE.get(key, defaultValue)
      Logger.debug(`读取Preferences[${key} = ${value}]成功`)
      return value
    } catch (e) {
      Logger.debug(`读取Preferences[${key}]失败`, JSON.stringify(e))
    }
  }
}

const preferenceUtil = new PreferenceUtil()

export default preferenceUtil as PreferenceUtil